import 'package:cbec_app/components/base/base_function.dart';
import 'package:cbec_app/components/common/my_coupon_item.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:cbec_app/components/base/base_chekbox.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

//优惠券弹窗
class RedpackPopup extends StatefulWidget {
  ///抵扣金额
  final double? amount;

  ///用券数量
  final int? couponNum;

  ///优惠券列表
  final List couponList;

  ///原价
  final double originPrice;

  ///回调
  final CallBackUseRedpack? callback;

  final List selectedRedPackIds;

  const RedpackPopup({
    super.key,
    required this.couponList,
    required this.selectedRedPackIds,
    this.callback,
    required this.originPrice,
    this.amount = 0.00,
    this.couponNum = 0,
  });

  @override
  State<RedpackPopup> createState() => _RedpackPopupState();
}

///被选中的优惠券ID
String couponIds = "";

///选中的优惠券数量
int choiseNum = 0;

///节省了多少钱
double amount = 0.00;

class _RedpackPopupState extends State<RedpackPopup> {
  @override
  void initState() {
    super.initState();
    choiseNum = widget.couponNum!;
    amount = widget.amount!;

    for (var coupon in widget.couponList) {
      coupon['selected'] = widget.selectedRedPackIds.contains(coupon['redPacketUserId']);
    }
  }

  @override
  Widget build(BuildContext context) {
    String typeTxt = '红包';
    return Container(
        width: 375.w,
        height: MediaQuery.of(context).size.height * 0.7,
        color: Tools.fromHex("#F3F5F7"),
        child: Container(
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 66.w,
                    decoration: BoxDecoration(color: Tools.fromHex("#FE5568"), borderRadius: const BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8))),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Expanded(
                            child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(typeTxt, style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#FFFFFF"))),
                            Text("可用$typeTxt${widget.couponList.length}", style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#FFFFFF"))),
                          ],
                        )),
                        BaseInteractive(
                          childWidget: Icon(
                            Icons.close,
                            color: Colors.white,
                            size: 15.w,
                          ),
                          onClick: () {
                            Get.back();
                          },
                        ),
                        SizedBox(width: 18.w)
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 10.w, top: 10.w),
                    child: Row(
                      children: [
                        Text("已选中推荐优惠，使用$typeTxt$choiseNum张，共抵扣",
                            style: setTextStyle(
                              12,
                              FontWeight.w300,
                              Tools.fromHex("#333333"),
                            )),
                        Text("￥$amount",
                            style: setTextStyle(
                              12,
                              FontWeight.w300,
                              Tools.fromHex("#F83F2D"),
                            ))
                      ],
                    ),
                  ),
                  Container(
                    height: 420.w,
                    padding: EdgeInsets.all(10.w),
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: widget.couponList.isNotEmpty
                            ? List.generate(widget.couponList.length, (index) {
                                final Map item = widget.couponList[index];
                                item['selected'] = item['selected'];
                                item['drop'] = item['price'];
                                item['name'] = item['redPacketName'];
                                item['goodsType'] = item['goodsType'];
                                item['validityStartTime'] = item['startTime'];
                                item['validityEndTime'] = item['endTime'];
                                item['discountDetails'] = "暂无使用说明";
                                item['actSuper'] = 1; //可以叠加使用
                                item['typeValue'] = 1; //红包全是满减
                                item['dropValue'] = item['price'];
                                item['couponUserId'] = item['redPacketUserId'];
                                return MyCouponItem(
                                    status: 0,
                                    item: item,
                                    rightWidgt: Container(
                                      margin: EdgeInsets.only(right: 10.w),
                                      child: BaseCheckBox(
                                        value: widget.couponList[index]['selected'] ?? false,
                                        onChange: (selected) {
                                          // change(item, index, selected);
                                          handleRedPacketSelection(item, widget.couponList);
                                        },
                                      ),
                                    ));
                              })
                            : [NotFound(txt: "暂无可用$typeTxt")],
                      ),
                    ),
                  ),
                ],
              ),
              Positioned(
                  bottom: MediaQuery.of(context).padding.bottom,
                  child: Container(
                    padding: EdgeInsets.fromLTRB(18.w, 5.w, 18.w, 5.w),
                    width: 375.w,
                    color: Colors.white,
                    child: solidButton('确定', () {
                      submit();
                    }),
                  ))
            ],
          ),
        ));
  }

// 封装红包选择逻辑
  void handleRedPacketSelection(Map selectedPacket, List allPackets) {
    setState(() {
      if (selectedPacket['superposition'] == 1) {
        // 可叠加的红包，取消所有不可叠加的红包，并将它们的 selected 改成 false
        for (var packet in allPackets) {
          if (packet['superposition'] == 0) {
            packet['selected'] = false; // 取消选中所有不可叠加红包
          }
        }

        if (selectedPacket['selected'] == true) {
          // 如果已经选中，点击则取消选中
          selectedPacket['selected'] = false;
        } else {
          // 否则设置当前选中的红包 selected 为 true
          selectedPacket['selected'] = true;
        }
      } else {
        // 不可叠加的红包，取消所有可叠加红包，并将它们的 selected 改为 false
        for (var packet in allPackets) {
          if (packet['superposition'] == 1) {
            packet['selected'] = false; // 取消选中所有可叠加红包
          }
        }
        // 只选择当前的不可叠加红包
        selectedPacket['selected'] = !selectedPacket['selected'];
      }

      // 重置合计的数值
      double totalDropValue = 0;
      String combinedCouponIds = '';
      int selectedCouponCount = 0;

      // 遍历所有红包，计算选中的红包的相关值
      for (var packet in allPackets) {
        if (packet['selected'] == true) {
          totalDropValue += packet['dropValue']; // 累加 dropValue
          combinedCouponIds += '${packet['couponUserId']},'; // 拼接 couponUserId
          selectedCouponCount++; // 统计选中的红包数量
        }
      }

      // 去掉 couponIds 最后多余的逗号
      if (combinedCouponIds.isNotEmpty) {
        combinedCouponIds = combinedCouponIds.substring(0, combinedCouponIds.length - 1);
      }
      // 更新状态
      amount = totalDropValue; // 将总 dropValue 赋值给 amount
      couponIds = combinedCouponIds; // 将拼接好的 couponUserId 字符串赋值给 couponIds
      choiseNum = selectedCouponCount; // 更新选中优惠券的数量
    });
  }

  //提交选择
  void submit() {
    // if (couponIds == '') {
    //   Tools.showToast("请先选择要使用的红包");
    // } else {
    //   widget.callback!(couponIds, amount.toString());
    //   Get.back();
    // }

    widget.callback!(couponIds, amount.toString());
    Get.back();
  }

  @override
  void dispose() {
    super.dispose();
  }
}

///唤起优惠券弹窗
void showRedPackPopup(
  List couponList,
  double price,
  CallBackUseRedpack callback,
  double amount,
  int couponNum,
  List selectedRedPackIds,
) {
  showCupertinoModalPopup(
    context: Get.context!,
    builder: (context) {
      return StatefulBuilder(builder: (context, setState) {
        return RedpackPopup(
          couponList: List.from(couponList), // 创建一个新的实例
          originPrice: price,
          callback: callback,
          amount: amount,
          couponNum: couponNum,
          selectedRedPackIds: List.from(selectedRedPackIds), // 确保参数变化
        );
      });
    },
  );
}
